package guoanmaker.operator.business.service;

import guoanmaker.operator.business.model.*;
import guoanmaker.operator.business.modelnobind.HotBusinessVO;
import guoanmaker.operator.business.modelnobind.ProvideCommodityMove;
import guoanmaker.operator.business.modelnobind.ProvideCommodityServiceMove;
import guoanmaker.operator.business.repository.*;
import guoanmaker.operator.helper.common.util.JsonUtil;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *  
 *
 * @ClassName: Operator2AppService 
 * @Description: Operator2AppService 
 * @author: huZhaoyu 
 * @date 2017/6/28 下午2:56 
 */
@Service
public class Operator2AppService implements Operator2AppServiceInterface {
    private final OperatorActivityTypeRepository operatorActivityTypeRepository;
    private final OperatorHotServerRepository operatorHotServerRepository;
    private final OperatorAppBannerRepository operatorAppBannerRepository;
    private final OperatorHeadlineRepository operatorHeadlineRepository;
    private final OperatorRoundPhotoAppRepository operatorRoundPhotoAppRepository;
    private final OperatorServerClassRepository operatorServerClassRepository;
    @Autowired
	private OperatorBoutiqueRecommendRepository operatorBoutiqueRecommendRepository;
    @Autowired
    private  OperatorHotwordsRepository operatorHotwordsRepository;
    @Autowired
	private OperatorRoomRepository operatorRoomRepository;
    @Autowired
    private OperatorPromotionNewRepository operatorPromotionNewRepository;
	@Autowired
	private OperatorHotBusinessNewForAPPRepository operatorHotBusinessNewForPCRepository;
	@Autowired
	private ProvideCommodityRepository provideCommodityRepository;
	@PersistenceContext
	private EntityManager manager;

    public Operator2AppService(OperatorActivityTypeRepository operatorActivityTypeRepository, OperatorHotServerRepository operatorHotServerRepository, OperatorAppBannerRepository operatorAppBannerRepository, OperatorHeadlineRepository operatorHeadlineRepository, OperatorRoundPhotoAppRepository operatorRoundPhotoAppRepository
                                , OperatorServerClassRepository operatorServerClassRepository) {
        this.operatorActivityTypeRepository = operatorActivityTypeRepository;
        this.operatorHotServerRepository = operatorHotServerRepository;
        this.operatorAppBannerRepository = operatorAppBannerRepository;
        this.operatorHeadlineRepository = operatorHeadlineRepository;
        this.operatorRoundPhotoAppRepository = operatorRoundPhotoAppRepository;
        this.operatorServerClassRepository = operatorServerClassRepository;
    }

    @Override
    public  HashMap<String, Object> getAll2App(String cityId) {
        HashMap<String, Object> reMap = new HashMap<>();
        try{
        long ban = operatorAppBannerRepository.count();
        List<OperatorAppBanner> banners = operatorAppBannerRepository.findBycityCode(cityId);
//        ArrayList<OperatorAppBanner> banners = new ArrayList(Arrays.asList(alls));
        if(banners.size()!=0){
        for (OperatorAppBanner  banner : banners){
        	if(banner.getBanType().equals("1")){
        		if(null!=banner.getItemLevel()&&!banner.getItemLevel().equals("")){
        		if(banner.getItemLevel()==1){
        			if(null!=banner.getServerFirstId()&&!banner.getServerFirstId().equals("")){
        			OperatorServerClass operatorServerClassOne = operatorServerClassRepository.findOne(banner.getServerFirstId());
        			banner.setServerName(operatorServerClassOne.getServerName());
        			if(null!=operatorServerClassOne.getServerType()){
        	            banner.setServerType(operatorServerClassOne.getServerType());}
        	           if(null!=operatorServerClassOne.getServerPicUrl()){
        	            	banner.setIconPath(operatorServerClassOne.getServerPicUrl());
        	            }
        			}
        		}else if(banner.getItemLevel()==2){
        			if(null!=banner.getServerId()&&!banner.getServerId().equals("")){
        			OperatorServerClass operatorServerClassTwo = operatorServerClassRepository.findOne(banner.getServerId());
        			banner.setServerName(operatorServerClassTwo.getServerName());
        			if(null!=operatorServerClassTwo.getServerType()){
        	            banner.setServerType(operatorServerClassTwo.getServerType());}
        	            if(null!=operatorServerClassTwo.getServerPicUrl()){
        	            	banner.setIconPath(operatorServerClassTwo.getServerPicUrl());
        	            }
        		}
        		}
        		}
        	}
        	}
        }
        reMap.put("banners", banners);
        List<OperatorHotServer> servers = operatorHotServerRepository.findBycityCode(cityId);//热门服务
        if(servers.size()!=0){
        for (OperatorHotServer operatorHotServer : servers) {
            OperatorServerClass serverClass = operatorServerClassRepository.findOne(operatorHotServer.getServerId());
            if(null!=serverClass.getServerName()){
            operatorHotServer.setServerName(serverClass.getServerName());}
            if(null!=serverClass.getServerType()){
            operatorHotServer.setServerType(serverClass.getServerType());}
        }
        }
        reMap.put("servers", servers);
        List<OperatorHeadline> headlines = operatorHeadlineRepository.findBycityCode(cityId);
        reMap.put("headlines", headlines);
        List<OperatorRoundPhotoApp> apps = operatorRoundPhotoAppRepository.findBycityCode(cityId);
        reMap.put("apps", apps);
        List<OperatorHotwords> hots=operatorHotwordsRepository.findByCityCodetwo(cityId);
        reMap.put("hots", hots);
        OperatorHotwords hot=operatorHotwordsRepository.findByCityCodeOne(cityId);
        reMap.put("hot", hot);
        Pageable pageable = new PageRequest(0,10);
        Page<OperatorBoutiqueRecommend> ofls=operatorBoutiqueRecommendRepository.findByCityCode(cityId,pageable);
        List<OutOperatorBoutiqueRecommend> outobrs=new ArrayList<OutOperatorBoutiqueRecommend>();
        
        for(OperatorBoutiqueRecommend obr:ofls){
        	OutOperatorBoutiqueRecommend outOperatorBoutiqueRecommend=new OutOperatorBoutiqueRecommend();
        	try{
        		if(obr.getProvideCommodityId().contains("S")){
	        		ProvideRoom provideRoom=operatorRoomRepository.findByroomCodes(obr.getProvideCommodityId());
	        		if(provideRoom!=null){
					outOperatorBoutiqueRecommend.setCommitName(provideRoom.getRoomName());
					outOperatorBoutiqueRecommend.setCommitid(provideRoom.getRoomCodes());
					outOperatorBoutiqueRecommend.setCommitUrl(provideRoom.getRoomlogo());
					outOperatorBoutiqueRecommend.setSynopsis(provideRoom.getDescribeAsk());
					outOperatorBoutiqueRecommend.setServerType(obr.getServerType());
					outOperatorBoutiqueRecommend.setCommodityId(provideRoom.getId());
					outobrs.add(outOperatorBoutiqueRecommend);
					}
	        		
	        	}else{
	        		ProvideCommodity provideCommodity=provideCommodityRepository.selectByCommodityForCodebq(Integer.parseInt(obr.getProvideCommodityId()));
	        		if(provideCommodity!=null){
	        		Double finalPrice=0.0;
	        		if(provideCommodity.getIsTerritoryRestriction().equals("2")){
	        			finalPrice=provideCommodity.getFinalPrice();
	        		}else if(provideCommodity.getIsTerritoryRestriction().equals("1")){
	        			String jpql2="select new guoanmaker.operator.business.modelnobind.ProvideCommodityServiceMove(s.id,ct.code,a.name,ct.name,p.name,ct.provincecode,s.isPromotion,s.commodityPrice,s.commodityPricePromotion,s.startTime,s.endTime,s.finalPrice)"
	        					+ " from ProvideCommodityServiceRange s left join  s.commodity c left join s.city ct left join s.area a left join s.province p  where  c.commodityCode=:commodityCode and ct.code=:code order by s.finalPrice";
	        			Query query2=manager.createQuery(jpql2);//查询商品提供的服务区域
	        			query2.setParameter("commodityCode", Integer.parseInt(obr.getProvideCommodityId()));
	        			query2.setParameter("code", cityId);
	        			List<ProvideCommodityServiceMove> lists=query2.getResultList();
	        			
	        			if(lists.size()>0){
	        				finalPrice=lists.get(0).getFinalPrice();
	        			}
	        		}
	        		
	        		
	        		System.out.println(provideCommodity.getCommodityCode()+"商品id");
	        		outOperatorBoutiqueRecommend.setCommitFinnalPrice(finalPrice);
					outOperatorBoutiqueRecommend.setCommitName(provideCommodity.getCommodityName());
					outOperatorBoutiqueRecommend.setCommitid(provideCommodity.getCommodityCode()+"");
					outOperatorBoutiqueRecommend.setCommitUrl(provideCommodity.getCommodity_smallimage());
					outOperatorBoutiqueRecommend.setSynopsis(provideCommodity.getSynopsis());
					outOperatorBoutiqueRecommend.setServerType(Integer.parseInt(provideCommodity.getType()));
					outOperatorBoutiqueRecommend.setCommodityId(provideCommodity.getId());
					outOperatorBoutiqueRecommend.setIsBargaining(provideCommodity.getIsBargaining());
        	
        	outobrs.add(outOperatorBoutiqueRecommend);
        	
	        		}
	        	}
        }catch(Exception e){
        	e.printStackTrace();
        }
		}
        
        reMap.put("ofls", outobrs);
        
        List<OperatorPromotionNew> protins= operatorPromotionNewRepository.selectByOperatorPromotionNew(cityId);

        reMap.put("protins", protins);
      //热门商户
      	List<OperatorHotBusinessNewForAPP> businessNewForPCs = operatorHotBusinessNewForPCRepository.findOperatorHotBusinessNewByCityCode(cityId);
      	List<HotBusinessVO> hotBusinessVOs = new ArrayList<>();
      	for (OperatorHotBusinessNewForAPP operatorHotBusinessNewForAPP : businessNewForPCs) {
      		String jpql = "select new guoanmaker.operator.business.modelnobind.HotBusinessVO(b.id,b.businessName,b.introduce,p.followNum) from "+
      				"ProvideShop  p left join p.providerBusiness b inner join b.personalUser u where u.isProvider=2 and  b.busNumber =:busNumber";
      		Query query = manager.createQuery(jpql);
      		query.setParameter("busNumber", operatorHotBusinessNewForAPP.getBusNumber());
      		List<HotBusinessVO>   businesss = query.getResultList();
      		if (businesss != null && businesss.size() >0) {
      			HotBusinessVO hotBusinessVO = businesss.get(0);
      			hotBusinessVO.setBusinesspicture(operatorHotBusinessNewForAPP.getBusPicture());
          		hotBusinessVOs.add(hotBusinessVO);
      		}
      		
		}
      	 reMap.put("hotBusinessVOs", hotBusinessVOs);
        }catch(Exception e){
        	e.printStackTrace();
        	System.out.println("精品推荐出现错误");
        }
        
      
      	 
        return reMap;
    }

}
